let redis = require('redis');

function RedisClient(options = {}){

	let ctx = {
		options: options,
		open: async function(){
			let client = await redis.createClient(options);
			ctx.redis = client;
		},
		set: function(key, val) {
			return new Promise(function (resolve, reject){
				ctx.redis.set(key, val, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		get: function(key) {
			return new Promise(function (resolve, reject){
				ctx.redis.get(key, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		keys: function(key) {
			return new Promise(function (resolve, reject){
				ctx.redis.keys(key, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		del: function(key) {
			return new Promise(function (resolve, reject){
				ctx.redis.del(key, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		hset: function(key, property, val) {
			return new Promise(function (resolve, reject){
				ctx.redis.hset(key, property, val, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		hget: function(key, property) {
			return new Promise(function (resolve, reject){
				ctx.redis.hget(key, property, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		}, 
		hdel: function(key, property) {
			return new Promise(function (resolve, reject){
				ctx.redis.hdel(key, property, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		}, 
		incrby: function(key, increment) {
			return new Promise(function (resolve, reject){
				ctx.redis.incrby(key, increment, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		decrby: function(key, increment) {
			return new Promise(function (resolve, reject){
				ctx.redis.decrby(key, increment, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		},
		close: async function(){
			return new Promise(function (resolve, reject){
				ctx.redis.end(false, function(err, res){
					if(err){
						reject(err);
					}else{
						resolve(res);
					}
				});
			});
		}
	};
	return ctx;
}

module.exports = {
	create: function(options) {
		return new RedisClient(options);
	}
};